package Leetcode.lc019;

import Leetcode.tools.ListNode;

/**
 *    删除链表最后第N个元素
 */
public class Sloution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode virtual = new ListNode(0, head);
        ListNode fast=virtual,slow=virtual;
        for(int i=0;i<n+1;i++){
            fast=fast.next;
        }
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return virtual.next;
    }

    public static void main(String[] args) {
        Sloution sloution = new Sloution();
        int[] ints = {1, 2, 3, 4,5};
        ListNode listNode = new ListNode(ints[0]);
        ListNode cur=listNode;
        for(int i=1;i<ints.length;i++){
            ListNode temp = new ListNode(ints[i]);
            cur.next=temp;
            cur=cur.next;
        }
        ListNode cobe=listNode;
        while (cobe!=null){
            System.out.print(cobe.val);
            cobe=cobe.next;
        }
        System.out.printf("%n");
        ListNode res=sloution.removeNthFromEnd(listNode,2);
        while (res!=null){
            System.out.print(res.val);
            res=res.next;
        }

    }
}

